package com.quxiu.file.controller;

import com.quxiu.file.service.ISysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.quxiu.common.core.domain.R;
import com.quxiu.common.core.utils.file.FileUtils;
import com.quxiu.system.api.domain.SysFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 文件请求处理
 *
 * @author quxiu
 */
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);
    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("/upload")
    public R<SysFile> upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            sysFile.setFullUrl(domain + url);
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    @RequestMapping("/download")
    @ResponseBody
    public void downloadFile(HttpServletResponse res, String filePath) throws Exception {
        String fileName = String.format("%s.%s", new Date().getTime(), FileUtils.getExtend(filePath));
        String mineType = new MimetypesFileTypeMap().getContentType(fileName);
        // attachment是以附件的形式下载，inline是浏览器打开
        res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        res.setContentType(mineType);
        InputStream is = sysFileService.downloadFile(filePath);
        byte[] bytes = FileUtils.streamToByteArray(is);
        ServletOutputStream os = res.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }
}
